package com.sharding.jdbc.demo.service.impl;

import com.sharding.jdbc.demo.entity.TableOne;
import com.sharding.jdbc.demo.mapper.TableOneMapper;
import com.sharding.jdbc.demo.service.TableOneService;
import com.sharding.jdbc.demo.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class TableOneServiceImpl implements TableOneService {

    @Resource
    private TableOneMapper tableOneMapper ;

    @Autowired
    @Qualifier("dataOneTemplate")
    private JdbcTemplate dataOneTemplate ;

    @Autowired
    @Qualifier("dataTwoTemplate")
    private JdbcTemplate dataTwoTemplate ;

    @Override
    public void createTable() {
        for (int i = 1 ; i <= 5 ; i++){
            String executeSQL = "CREATE TABLE table_one_"+i+" (\n" +
                    "  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',\n" +
                    "  `phone` varchar(20) NOT NULL COMMENT '手机号',\n" +
                    "  `name` varchar(50) DEFAULT NULL COMMENT '备用1',\n" +
                    "  `sex` varchar(50) DEFAULT NULL COMMENT '备用2',\n" +
                    "  PRIMARY KEY (`id`),\n" +
                    "  KEY `phoneIndex` (`phone`)\n" +
                    ") ENGINE=InnoDB DEFAULT CHARSET=utf8;" ;
            dataOneTemplate.execute(executeSQL);
            dataTwoTemplate.execute(executeSQL);
        }
    }

    @Override
    public void insertOne() {
        for (int i = 0 ; i < 20 ; i++){
            Long id = new SnowFlake(5,6).nextId(false);
            TableOne tableOne = new TableOne() ;
            tableOne.setId(id);
            tableOne.setPhone("188136777"+i);
            tableOne.setName("张三"+i);
            tableOne.setSex("男");
            tableOneMapper.insert(tableOne) ;
        }
    }

    @Override
    public List<TableOne> selectOneByPhone(String phone) {
        return tableOneMapper.selectOneByPhone(phone);
    }
}
